package com.thp.proxy.custom;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 自定义的ClassLoader
 * 
 * 实现的功能:
 *   代码的生成,编译,重新动态load到JVM中
 * @author Tommy
 *
 */
public class MyClassLoader extends ClassLoader {
	
	
	
	private File baseDir;
	
	public MyClassLoader() {
		// 获取当前的运行路径
		String basePath = MyClassLoader.class.getResource("").getPath();
		this.baseDir = new File(basePath);
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String className = MyClassLoader.class.getPackage().getName() + "." + name;  // 包名字.类名字
		if(baseDir != null) {
			
			File classFile = new File(baseDir,name.replaceAll("\\.", "/") + ".class");
			
			if(classFile.exists()) {
				FileInputStream in = null;
				ByteArrayOutputStream out = null; 
				try {
					in = new FileInputStream(classFile);
					// ByteArray   类是一个字节码文件
					out = new ByteArrayOutputStream();
					byte[] buff = new byte[1024];
					int len;
					while((len = in.read(buff)) != -1) {
						out.write(buff, 0, len);
					}
					System.out.println("------" + className);
					
					// defineClass 是JVM的方法
					return defineClass(className, out.toByteArray(), 0, out.size());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					// 删除.class文件
					System.out.println(classFile.getAbsolutePath());
					
					// 操作JVM是一定要关流的,不关闭的话,会有麻烦的
					if(in != null) {
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						} finally {
							in = null;
						}
					}
					if(out != null) {
						try {
							out.close();
						} catch (IOException e) {
							e.printStackTrace();
						} finally {
							out = null;
						}
					}
					// 一定要关流之后 才能够成功删除
					// System.out.println(classFile.delete());
				}
			}
		}
		
		return null;
	}
	
	
	
}
